#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
@File    :  temp_DAQ_upload.py
@Time    :  2022/05/23 14:42:15
@Author  :  HHLiang
@Contact :  sternapeg@qq.com
@Version :  1.0
@Desc    :  采集数据并上传云平台
'''
# import ctypes
# import sys

from config import config_run
from get_temp.pyTherm import main
from edp_sdk import *


def get_CPU_Temp():
    """
    它返回当前时间和当前 CPU 温度的元组
    :return: 包含当前时间和 CPU 温度的元组。
    """

    get_temps = main()
    cpu_temp = json.loads(get_temps)
    pc_name = 'HHL-OWNER'  # 需要个人依据自己电脑名称情况自行修改。
    cpu_temp = cpu_temp[pc_name][-2]['Reading'][:-2]  # 根据自己电脑配置，可能需要修改
    cpu_temp = float(cpu_temp)  # 字符串转为浮点数

    return(cpu_temp)

# def is_admin():
#     try:
#         return ctypes.windll.shell32.IsUserAnAdmin()
#     except:
#         return False
# # 获取管理员权限
# if is_admin():
#     # Code of your program here
#     # 读取温度
#     cpu_temp = get_CPU_Temp()
#     data = {'temp': {t: cpu_temp}}
    
# else:
#     # Re-run the program with admin rights
#     ctypes.windll.shell32.ShellExecuteW(
#         None, "runas", sys.executable, __file__, None, 1)


if __name__ == '__main__':

    
    # 以下设备和产品信息，请自行补全
    # api_key = 'XXXXXXXXXXXXX'    # 设备APIkey
    # product_id = 'XXXXXX'        # 产品ID
    # device_id = 'XXXXXXXXX'      # 设备ID
    # auth_info = 'XXXXXXXXXXXX'   # 鉴权信息

    config = config_run('A1')
    api_key = config[0]
    product_id = config[1]
    device_id = config[2]
    auth_info = config[3]

    host = config[4]
    port = config[5]

    # 创建Sockey连接
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 建立连接
    s.connect((host, port))
    # 发送登录报文， 并接收响应
    conn_msg = gen_conn_msg(pid=product_id, auth_info=auth_info)
    # print(conn_msg)
    s.send(conn_msg)
    # 接收响应并打印
    resp = s.recv(1024)
    print('设备注册结果：', resp)

    while True:
        # 获取时间
        t = time.strftime("%Y-%m-%d %H:%M:%S")
        # t = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
        # 采集温度
        print("获取电脑CPU温度!")
        cpu_temp = get_CPU_Temp()
        data = {'temp': {t: cpu_temp}}
        print(data)
        # print(cpu_temp)
        # 以数据类型四进行组包并发送数据
        t4_data = save_type4(json.dumps(data), 1)
        print("开始上传数据！")
        s.send(t4_data)
        print('data: ', t4_data)
        # 接收反馈信息并打印
        resp = s.recv(1024)
        print('recv: ', resp)
        # 定时5秒
        time.sleep(5)

        